import React, { useState, useEffect } from 'react';
import { Table, Card, Spin, message, Input, Modal, Form, InputNumber, Button, Tag, Tooltip, Badge } from 'antd';
import { useNavigate } from 'react-router-dom';
import { $fetchStockList, $buyStock, $sellStock } from '../../api/stockApi';
import './StockList.scss';
import dayjs from 'dayjs';
import { 
  RiseOutlined, 
  FallOutlined, 
  SearchOutlined, 
  ShoppingCartOutlined, 
  DollarOutlined,
  ArrowUpOutlined,
  TrendingDownOutlined,
  FireOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';

const { Search } = Input;

const getUserId = () => {
  const userInfo = localStorage.getItem('user_info');
  if (!userInfo) throw { msg: '用户未登录或未找到用户信息' };

  try {
      const parsedUserInfo = JSON.parse(userInfo);
      return parsedUserInfo.id;
  } catch (error) {
      throw { msg: '用户信息解析失败' };
  }
};

const StockList = () => {
  const [data, setData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isBuyModalVisible, setIsBuyModalVisible] = useState(false);
  const [isSellModalVisible, setIsSellModalVisible] = useState(false);
  const [selectedStock, setSelectedStock] = useState(null);
  const [userAssets, setUserAssets] = useState([]);
  const navigate = useNavigate();

  useEffect(() => {
    setLoading(true);
    $fetchStockList()
      .then(list => {
        const formatted = list.map(item => ({
          symbol: item.symbol,
          name: item.name,
          price: item.price,
          changeRate: item.change_rate,
          change: item.change,
          volume: item.volume,
          amount: (item.amount / 100000000).toFixed(2),
          turnover: item.turnover_rate,
          amplitude: item.amplitude,
          high: item.high,
          low: item.low,
          open: item.open,
          prevClose: item.prev_close,
          volumeRate: item.volume_rate,
          pe: item.pe,
          pb: item.pb
        }));
        setData(formatted);
        setFilteredData(formatted);
      })
      .catch(err => {
        console.error('fetch stock list error:', err);
        message.error(`获取股票列表失败：${err.message}`);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  const handleSearch = (value) => {
    const searchValue = value.trim().toLowerCase();
    if (!searchValue) {
      setFilteredData(data);
    } else {
      const filtered = data.filter(item =>
        item.symbol.toLowerCase().includes(searchValue) ||
        item.name.toLowerCase().includes(searchValue)
      );
      setFilteredData(filtered);
    }
  };

  const handleBuyStock = (stock) => {
    setSelectedStock(stock);
    setIsBuyModalVisible(true);
  };

  const handleSellStock = (stock) => {
    setSelectedStock(stock);
    setIsSellModalVisible(true);
  };

  const handleBuySubmit = async (values) => {
    try {
      const userid = getUserId();
        if (!userid) {
            message.error('用户未登录，请先登录');
            return;
        }

      await $buyStock({
        userid: parseInt(userid, 10),
        products_id: selectedStock.symbol,
        products_name: selectedStock.name,
        quantity: values.quantity,
        price: selectedStock.price,
        trade_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
      });
      message.success('购买成功');
      setIsBuyModalVisible(false);
    } catch (error) {
      message.error(error.msg || '购买失败');
    }
  };

  const handleSellSubmit = async (values) => {
    try {
      await $sellStock({
        userid: getUserId(),
        products_id: selectedStock.symbol,
        products_name: selectedStock.name,
        quantity: values.quantity,
        price: selectedStock.price
      });
      message.success('卖出成功');
      setIsSellModalVisible(false);
    } catch (error) {
      message.error(error.msg || '卖出失败');
    }
  };

  // 渲染涨跌幅标签
  const renderChangeRate = (changeRate, change) => {
    const isPositive = parseFloat(changeRate) > 0;
    const isNegative = parseFloat(changeRate) < 0;
    
    if (isPositive) {
      return (
        <Tag color="red" className="change-tag positive">
          <RiseOutlined /> {changeRate}%
        </Tag>
      );
    } else if (isNegative) {
      return (
        <Tag color="green" className="change-tag negative">
          <FallOutlined /> {changeRate}%
        </Tag>
      );
    } else {
      return (
        <Tag color="default" className="change-tag neutral">
          {changeRate}%
        </Tag>
      );
    }
  };

  // 渲染涨跌额
  const renderChange = (change) => {
    const value = parseFloat(change);
    const className = value > 0 ? 'positive-text' : value < 0 ? 'negative-text' : 'neutral-text';
    return <span className={className}>{change}</span>;
  };

  // 渲染价格
  const renderPrice = (price, changeRate) => {
    const rate = parseFloat(changeRate);
    const className = rate > 0 ? 'positive-text' : rate < 0 ? 'negative-text' : 'neutral-text';
    return <span className={`price-text ${className}`}>¥{price}</span>;
  };

  // 渲染成交量标签
  const renderVolume = (volume) => {
    const vol = parseInt(volume);
    if (vol > 1000000) {
      return (
        <Badge count={<FireOutlined style={{ color: '#ff4d4f' }} />}>
          <span className="volume-text">{(vol / 10000).toFixed(1)}万</span>
        </Badge>
      );
    }
    return <span className="volume-text">{(vol / 10000).toFixed(1)}万</span>;
  };

  const columns = [
    { 
      title: '序号', 
      dataIndex: 'index', 
      key: 'index', 
      width: 60, 
      render: (_, __, idx) => (
        <div className="index-cell">
          {idx + 1}
        </div>
      )
    },
    {
      title: '股票信息',
      key: 'stockInfo',
      width: 200,
      render: (_, record) => (
        <div className="stock-info-cell">
          <div className="stock-symbol">
            <a
              onClick={() => navigate(`/stock/kline?symbol=${record.symbol}`)}
              className="symbol-link"
            >
              {record.symbol}
            </a>
          </div>
          <div className="stock-name">{record.name}</div>
        </div>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <div className="action-buttons">
          <Button 
            type="primary" 
            size="small"
            icon={<ShoppingCartOutlined />}
            onClick={() => handleBuyStock(record)} 
            className="buy-button"
          >
            买入
          </Button>
          <Button 
            danger 
            size="small"
            icon={<DollarOutlined />}
            onClick={() => handleSellStock(record)}
            className="sell-button"
          >
            卖出
          </Button>
        </div>
      )
    },
    { 
      title: '最新价', 
      dataIndex: 'price', 
      key: 'price', 
      width: 100,
      render: (price, record) => renderPrice(price, record.changeRate)
    },
    { 
      title: '涨跌幅', 
      key: 'changeRate', 
      width: 120,
      render: (_, record) => renderChangeRate(record.changeRate, record.change)
    },
    { 
      title: '涨跌额', 
      dataIndex: 'change', 
      key: 'change', 
      width: 100,
      render: renderChange
    },
    { 
      title: '成交量', 
      dataIndex: 'volume', 
      key: 'volume', 
      width: 120,
      render: renderVolume
    },
    { 
      title: '成交额', 
      dataIndex: 'amount', 
      key: 'amount', 
      width: 120,
      render: (amount) => (
        <Tooltip title={`${amount}亿元`}>
          <span className="amount-text">{amount}亿</span>
        </Tooltip>
      )
    },
    { 
      title: '换手率', 
      dataIndex: 'turnover', 
      key: 'turnover', 
      width: 100, 
      render: v => (
        <Tag color={parseFloat(v) > 10 ? 'volcano' : 'blue'} className="turnover-tag">
          {v}%
        </Tag>
      )
    },
    { 
      title: '振幅', 
      dataIndex: 'amplitude', 
      key: 'amplitude', 
      width: 100, 
      render: v => (
        <span className={parseFloat(v) > 5 ? 'high-amplitude' : 'normal-amplitude'}>
          {v}%
        </span>
      )
    },
    { title: '最高', dataIndex: 'high', key: 'high', width: 100, render: v => <span className="high-price">¥{v}</span> },
    { title: '最低', dataIndex: 'low', key: 'low', width: 100, render: v => <span className="low-price">¥{v}</span> },
    { title: '今开', dataIndex: 'open', key: 'open', width: 100, render: v => <span className="open-price">¥{v}</span> },
    { title: '昨收', dataIndex: 'prevClose', key: 'prevClose', width: 100, render: v => <span className="prev-close">¥{v}</span> },
    { 
      title: '量比', 
      dataIndex: 'volumeRate', 
      key: 'volumeRate', 
      width: 100,
      render: v => (
        <Tag color={parseFloat(v) > 2 ? 'red' : parseFloat(v) > 1 ? 'orange' : 'default'}>
          {v}
        </Tag>
      )
    },
    { 
      title: '市盈率', 
      dataIndex: 'pe', 
      key: 'pe', 
      width: 120,
      render: v => <span className="pe-text">{v}</span>
    },
    { 
      title: '市净率', 
      dataIndex: 'pb', 
      key: 'pb', 
      width: 100,
      render: v => <span className="pb-text">{v}</span>
    }
  ];

  return (
    <div className="stock-list-page">
      <div className="page-header">
        <div className="header-content">
          <div className="header-title">
            <ArrowUpOutlined className="header-icon" />
            <h1>沪A股实时行情</h1>
            <Badge count={filteredData.length} className="stock-count-badge" />
          </div>
          <div className="market-stats">
            <div className="stat-item">
              <ThunderboltOutlined />
              <span>实时更新</span>
            </div>
          </div>
        </div>
      </div>

      <Card className="stock-card" bordered={false}>
        <div className="search-section">
          <Search
            placeholder="输入股票代码或名称进行搜索..."
            allowClear
            enterButton={<SearchOutlined />}
            onSearch={handleSearch}
            className="stock-search"
            size="large"
          />
        </div>
        
        {loading ? (
          <div className="loading-container">
            <Spin size="large" tip="正在加载股票数据..." />
          </div>
        ) : (
          <div className="table-container">
            <Table
              rowKey="symbol"
              dataSource={filteredData}
              columns={columns}
              pagination={{ 
                pageSize: 20,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `共 ${total} 只股票，显示第 ${range[0]}-${range[1]} 条`
              }}
              scroll={{ x: 'max-content', y: 600 }}
              className="stock-table"
              rowClassName={(record, index) => {
                const changeRate = parseFloat(record.changeRate);
                if (changeRate > 0) return 'positive-row';
                if (changeRate < 0) return 'negative-row';
                return 'neutral-row';
              }}
            />
          </div>
        )}
      </Card>

      {/* 购买弹窗 */}
      <Modal
        title={
          <div className="modal-title">
            <ShoppingCartOutlined />
            <span>购买股票</span>
          </div>
        }
        visible={isBuyModalVisible}
        onCancel={() => setIsBuyModalVisible(false)}
        footer={null}
        className="trade-modal buy-modal"
      >
        {selectedStock && (
          <div className="stock-info-modal">
            <div className="selected-stock">
              <div className="stock-code">{selectedStock.symbol}</div>
              <div className="stock-name-modal">{selectedStock.name}</div>
              <div className="current-price">当前价格: ¥{selectedStock.price}</div>
            </div>
          </div>
        )}
        <Form onFinish={handleBuySubmit} layout="vertical">
          <Form.Item 
            label="购买数量（股）" 
            name="quantity" 
            rules={[{ required: true, message: '请输入购买数量' }]}
          >
            <InputNumber 
              min={100} 
              step={100} 
              style={{ width: '100%' }}
              placeholder="最小100股，以100股为单位"
            />
          </Form.Item>
          <Form.Item className="modal-buttons">
            <Button 
              type="primary" 
              htmlType="submit"
              size="large"
              icon={<ShoppingCartOutlined />}
              className="confirm-buy-btn"
            >
              确认购买
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 卖出弹窗 */}
      <Modal
        title={
          <div className="modal-title">
            <DollarOutlined />
            <span>卖出股票</span>
          </div>
        }
        visible={isSellModalVisible}
        onCancel={() => setIsSellModalVisible(false)}
        footer={null}
        className="trade-modal sell-modal"
      >
        {selectedStock && (
          <div className="stock-info-modal">
            <div className="selected-stock">
              <div className="stock-code">{selectedStock.symbol}</div>
              <div className="stock-name-modal">{selectedStock.name}</div>
              <div className="current-price">当前价格: ¥{selectedStock.price}</div>
            </div>
          </div>
        )}
        <Form onFinish={handleSellSubmit} layout="vertical">
          <Form.Item 
            label="卖出数量（股）" 
            name="quantity" 
            rules={[{ required: true, message: '请输入卖出数量' }]}
          >
            <InputNumber 
              min={100} 
              step={100} 
              style={{ width: '100%' }}
              placeholder="最小100股，以100股为单位"
            />
          </Form.Item>
          <Form.Item className="modal-buttons">
            <Button 
              danger 
              htmlType="submit"
              size="large"
              icon={<DollarOutlined />}
              className="confirm-sell-btn"
            >
              确认卖出
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StockList;